package com.library.interceptor;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author : 雾眠气泡水
 * @Date : 2024/9/15 -- 16:59
 * @Description :
 */

@WebFilter("/*")
public class UserFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("UTF-8");
        servletResponse.setCharacterEncoding("UTF-8");
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        if (uri.endsWith("login.jsp") || uri.endsWith("loginServlet") || uri.endsWith("register.jsp") || uri.endsWith("RegisterServlet")) {
            filterChain.doFilter(request, response);
            return;
        }
        HttpSession session = request.getSession();
        if (session.getAttribute("logUser") == null) {
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }
        filterChain.doFilter(request, response);
    }
}
